import { Command } from '../constant';
import { IMainReducer } from '../types';
import { Action } from 'typings';
import produce from 'immer';
import * as immerUtil from '@/redux/immer-util';

const INITIAL_STATE: IMainReducer = {
  isReady: false,
  isLoading: false,
  consigneeName: '',//收货人
  consigneeNumber: '',//收货人手机号码
  deliveryAddress: '',//详细地址
  isDefaltAddress: 0,//是否默认地址:0: 否,1: 是
  deliveryAddressId: null,
  latitude: null,//纬度
  longitude: null,//经度
  areaIds: [],
  areaInfo: '',
  pickerShow: false,//地址弹出层
  provinceId: null,
  cityId: null,
  areaId: null,
};

export default function main(state = INITIAL_STATE, action: Action): IMainReducer {
  const { type, payload } = action;

  return produce<IMainReducer>(state, (draftState) => {
    switch (type) {
      //通用改变数据
      case Command.commonChange:
        return immerUtil.commonChange(draftState, { ...payload, key: 'main' });

      //初始化
      case Command.init:
        draftState.isReady = true;
        for (let propKey in payload.main) {
          draftState[propKey] = payload.main[propKey];
        }
        return draftState;

      //重置
      case Command.clean:
        for (let propKey in INITIAL_STATE) {
          draftState[propKey] = INITIAL_STATE[propKey];
        }
        return draftState;
    }
  });
}
